<template>
  <div class="service-management-add">
    <el-card>
      <div class="card-header">
        <span>添加服务</span>
      </div>
      
      <el-form :model="serviceForm" :rules="rules" ref="serviceForm" label-width="120px">
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="serviceForm.serviceName" placeholder="请输入服务名称" maxlength="100"></el-input>
        </el-form-item>
        
        <el-form-item label="服务类型" prop="serviceTypeId">
          <el-select v-model="serviceForm.serviceTypeId" placeholder="请选择服务类型">
            <el-option v-for="type in serviceTypes" :key="type.id" :label="type.typeName" :value="type.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属设备" prop="deviceId">
          <el-select v-model="serviceForm.deviceId" placeholder="请选择所属设备">
            <el-option v-for="device in devices" :key="device.id" :label="device.deviceName" :value="device.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="服务状态" prop="status">
          <el-select v-model="serviceForm.status" placeholder="请选择服务状态">
            <el-option label="运行中" value="RUNNING"></el-option>
            <el-option label="已停止" value="STOPPED"></el-option>
            <el-option label="错误" value="ERROR"></el-option>
            <el-option label="置备中" value="PROVISIONING"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="serviceForm.description" placeholder="请输入描述信息" type="textarea" maxlength="500" show-word-limit></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ServiceManagementAdd',
  data() {
    return {
      serviceForm: {
        serviceName: '',
        serviceTypeId: '',
        deviceId: '',
        status: 'RUNNING',
        description: ''
      },
      serviceTypes: [],
      devices: [],
      rules: {
        serviceName: [
          { required: true, message: '请输入服务名称', trigger: 'blur' },
          { max: 100, message: '服务名称不能超过100个字符', trigger: 'blur' }
        ],
        serviceTypeId: [
          { required: true, message: '请选择服务类型', trigger: 'change' }
        ],
        deviceId: [
          { required: true, message: '请选择所属设备', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择服务状态', trigger: 'change' }
        ],
        description: [
          { max: 500, message: '描述信息不能超过500个字符', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    this.loadServiceTypes();
    this.loadDevices();
  },
  methods: {
    loadServiceTypes() {
      this.$api.serviceTypeApi.getAll()
        .then(res => {
          this.serviceTypes = res && res.data || [];
        })
        .catch(error => {
          console.error('获取服务类型失败:', error);
          this.$message.error('获取服务类型失败');
        });
    },
    
    loadDevices() {
      this.$api.deviceApi.getAll()
        .then(res => {
          this.devices = res && res.data || [];
        })
        .catch(error => {
          console.error('获取设备列表失败:', error);
          this.$message.error('获取设备列表失败');
        });
    },
    
    handleSubmit() {
      this.$refs.serviceForm.validate((valid) => {
        if (valid) {
          // 检查服务名称在同一设备下是否已存在
          this.$api.syncTaskApi.getAll({
            serviceName: this.serviceForm.serviceName,
            deviceId: this.serviceForm.deviceId
          }).then(res => {
            const services = res && res.data || [];
            const exists = services.some(service => 
              service.serviceName === this.serviceForm.serviceName && 
              service.deviceId === this.serviceForm.deviceId
            );
            
            if (exists) {
              this.$message.error('该设备下已存在同名服务');
              return;
            }
            
            // 提交表单
            this.$api.syncTaskApi.add(this.serviceForm)
              .then(() => {
                this.$message.success('服务添加成功');
                this.$router.push('/service-management');
              })
              .catch(error => {
                console.error('添加服务失败:', error);
                this.$message.error('添加服务失败: ' + error.message);
              });
          }).catch(error => {
            console.error('检查服务名称失败:', error);
            // 继续提交，让后端进行验证
            this.$api.syncTaskApi.add(this.serviceForm)
              .then(() => {
                this.$message.success('服务添加成功');
                this.$router.push('/service-management');
              })
              .catch(error => {
                console.error('添加服务失败:', error);
                this.$message.error('添加服务失败: ' + error.message);
              });
          });
        }
      });
    },
    
    handleCancel() {
      this.$router.push('/service-management');
    }
  }
};
</script>

<style scoped>
.service-management-add {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>